package com.globallogic.dailyplanner.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import com.globallogic.dailyplanner.dto.RoleEnum;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(userDetailsService)
			.passwordEncoder(shaPasswordEncoder());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.authorizeRequests()
			.antMatchers("/views/registration.xhtml").permitAll()
	        .antMatchers("/views/**").hasAnyRole(RoleEnum.USER.name(),RoleEnum.ADMIN.name())
	        .antMatchers("/views/admin/**").hasRole(RoleEnum.ADMIN.name())
	        .and()
	        .formLogin()
	        .loginPage("/views/login.xhtml")
	        .failureUrl("/views/403.html")
	        .permitAll()
	        .and()
	        .logout().logoutUrl("/logout")
	        .invalidateHttpSession(true)
	        .permitAll();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web
			.ignoring()
			.antMatchers("/resources/**");
	}
	
	@Bean
	public ShaPasswordEncoder shaPasswordEncoder(){
		ShaPasswordEncoder encoder = new ShaPasswordEncoder(256);
		
		return encoder;
	}
	
}
